package org.tnaggs.project.controller;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.validation.ValidationUtils;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import org.tnaggs.project.manager.ContactManager;
import org.tnaggs.project.manager.LeagueManager;
import org.tnaggs.project.manager.LocationManager;
import org.tnaggs.project.manager.PlayerManager;
import org.tnaggs.project.model.Contact;
import org.tnaggs.project.model.League;
import org.tnaggs.project.model.Location;
import org.tnaggs.project.model.PasswordChange;
import org.tnaggs.project.model.Player;
import org.tnaggs.project.model.Team;
import org.tnaggs.project.security.ContactUser;
import org.tnaggs.project.validate.PasswordValidator;
import org.tnaggs.project.view.PlayerView;



@Controller
@RequestMapping("/contact")
public class ContactController {

	@Autowired
	private ContactManager conManager;
	
	@Autowired
	private LeagueManager laxManager;
	
	@Autowired
	private LocationManager locationManager;
	
	@Autowired
	private PlayerManager playerManager;
	
	@RequestMapping(value = "/changePassword.html", method = RequestMethod.GET)
	public ModelAndView viewChangePwd(@RequestParam("id") int contactID) {
		ModelAndView results = new ModelAndView("changePassword");
		
		results.addObject("commandPassword", new PasswordChange());
		results.addObject("contact", conManager.getContact(contactID));
		return results;
	}
	
	@RequestMapping(value = "/changePassword.html", method = RequestMethod.POST)
	public String changePwd(@RequestParam("id") int contactID, PasswordChange newPass, BindingResult result, Map<Object, Object> model) {
		
		Contact contact = conManager.getContact(contactID);
		if(!contact.getPassword().equalsIgnoreCase(newPass.getPreviousAttempt())) {
			result.addError(new ObjectError("pass.wrong", "Old Password Incorrect"));
		}
		ValidationUtils.invokeValidator(new PasswordValidator(), newPass, result);
		if(!result.hasErrors()) {
			conManager.changePassword(contactID, newPass.getSecondAttempt());
		  return "redirect:/contact/view.html?id=" + contactID;
		}
		else {
			List<String> errors = new ArrayList<String>();
			for(ObjectError error : result.getAllErrors()) {
				errors.add(error.getDefaultMessage());
			}
			model.put("errors", errors);
			model.put("contact", conManager.getContact(contactID));
			model.put("commandPassword", new PasswordChange());
		  return "changePassword";
		}
	}
	
	@RequestMapping(value = "/addContact.html", method = RequestMethod.POST)
    public String addContact(@ModelAttribute("contact")
                            Contact contact, BindingResult result) {
         
        conManager.createContact(contact);
         
        return "redirect:/index.html";
    }
	
	@RequestMapping(value = "/view.*", method = RequestMethod.GET)
	public ModelAndView viewContact(@RequestParam("id") int contactID) {
		 ModelAndView mav = new ModelAndView("viewContact");
		 
		 Contact contact = conManager.getContact(contactID);
		 
		 List<League> adminLeagues = new ArrayList<League>();
		 List<Team> coachedTeams = new ArrayList<Team>();
		 List<PlayerView> playedTeams = new ArrayList<PlayerView>();
		 List<Location> locationsPOC = new ArrayList<Location>();
		 
		 List<Location> locals = locationManager.getAllLocations();
		 for(Location local : locals) {
			 if(local.getContactID() == contact.getContactID()) {
				locationsPOC.add(local); 
			 }
		 }
		 
		 List<League> teams = laxManager.getAllLeagues();
		 
		 for(League league : teams) {
			 if(league.getAdmin() == contact.getContactID()) {
				 adminLeagues.add(league); 
			}
			List<Team> teamsInLeague = laxManager.getTeams(league.getLeagueName());
			for(Team team : teamsInLeague) {
			  if(team.getContactID() == contact.getContactID()) {
						 coachedTeams.add(team);
			  }
		      List<Player> players = playerManager.getPlayers(team.getTeamID());
			  for(Player player : players) {
			    if(contact.getContactID() == player.getContactID()) {
			    	PlayerView playerV = new PlayerView();
			    	playerV.setTeam(team);
			    	playerV.setPlayer(player);
			    	playerV.setContact(contact);
				 playedTeams.add(playerV);
			    }
			  }
		    }
		  }
			 
		 mav.addObject("adminLeagues", adminLeagues);
		 mav.addObject("coachedTeams", coachedTeams);
		 mav.addObject("playedTeams", playedTeams);
		 mav.addObject("locationsPOC", locationsPOC);
		 mav.addObject("contact", contact);
		 
		 		 
		 ContactUser user = null;
	     Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
	     if(principal instanceof UserDetails){
	       user = (ContactUser)principal;
	     } 
	     if(user != null) {
	       mav.addObject("principal", user.getContact());
	     } else {
	       mav.addObject("principal", "anonymous");	
	     }
	        
	        
		 return mav;
	}

	public ContactManager getConManager() {
		return conManager;
	}

	public void setConManager(ContactManager conManager) {
		this.conManager = conManager;
	}
	
	
}
